package com.example.dollarShipping.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dollarShipping.entity.*;
import com.example.dollarShipping.mapper.*;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AccountService {
    @Resource
    ShippingOrderService shippingOrderService;
    @Resource
    UserMapper userMapper;
    @Resource
    CarrierService carrierService;
    @Resource
    OperationRecordMapper operationRecordMapper;
    @Resource
    TruckOrderMapper truckOrderMapper;

    public List<ShippingOrder> getShippingOrder(Long id) {
        return shippingOrderService.getShippingOrder(id,null,null);
    }

    public void createShippingOrder(ShippingOrder s) {
        User u = userMapper.selectById(s.getCreatorId());
        s.setTime(new Date());
        s.setCreatorName(u.getRealName());
        shippingOrderService.createOrder(s);
    }


    public String changeState(Integer state, Long id, Long operator) {
        ShippingOrder s = shippingOrderService.selectById(id);
        String res = null;
        switch (state) {
            case 8:
                s.setState(7);
                s = settle(s);
                res = "已签收";
                break;
            case 9:
                s.setState(8);
                res = "结算完成";
        }
        shippingOrderService.updateOrder(s);
        OperationRecord task = new OperationRecord(1,id,state,operator,new Date());
        operationRecordMapper.insert(task);
        return res;
    }

    private ShippingOrder settle(ShippingOrder s) {
        List<TruckOrder> tl = truckOrderMapper.selectList(new QueryWrapper<TruckOrder>().eq("order_id",s.getId()));
        double unexpectedCost = 0;
        for(TruckOrder t:tl){
            unexpectedCost+=t.getUnexpectedCost();
        }
        s.setUnexpectedCost(unexpectedCost);
        s.setTotalPrice(s.getLogisticsCost()+unexpectedCost);
        return s;
    }


    public void delete(Long id) {
        shippingOrderService.delete(id);
    }
    public ShippingOrder findShippingOrder(Long orderId) {
        return shippingOrderService.findShippingOrder(orderId);
    }


}
